
// 云函数入口文件
const cloud = require('wx-server-sdk')
// const db = cloud.database()
cloud.init({
  env: "zmyy-6uke0"
})
// 云函数入口函数
// exports.main = async (event, context) => {
//   let { gz_address,database} =event
//   return await cloud.database().collection(database)
//     .where({    //数据库名称txl
//       _openid: "oL22f4qviFt-rMECN4sH59EW-q4s",
//       // gz_address: "静湖南苑"
//       // gz_address: cloud.database().command.eq(gz_address)
//     })
//     //.orderBy('name', 'desc')//按字段排序
//     .get()
// }


//获取集合所有数据
const db = cloud.database()
const MAX_LIMIT = 1000
exports.main = async (event, context) => {
  let { gz_address, database, gzry_addtime } = event
  // 先取出集合记录总数
  const countResult = await db.collection(database).count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 1000)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    const promise = db.collection(database).where({
      // _openid: "oL22f4qviFt-rMECN4sH59EW-q4s",
      gz_address: gz_address,
      gzry_addtime: db.command.gt(gzry_addtime)
    }).orderBy('gzry_addtime', 'desc')
        // .orderBy('gzry_addtime', 'desc')
    .skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => {
    return {
      length: acc.data.length,
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })


}

